package com.xzwzz.kotlindemo

import com.alibaba.fastjson.JSONArray
import java.io.*
import java.util.ArrayList
import java.util.Objects
import java.util.Scanner
import java.io.IOException
import jdk.nashorn.internal.runtime.ScriptingFunctions.readLine
import java.io.InputStreamReader
import java.io.BufferedReader
import java.io.FileInputStream
import java.util.concurrent.Executors
import java.io.BufferedInputStream
import java.util.zip.ZipEntry
import java.io.File
import java.util.zip.ZipOutputStream
import java.io.FileOutputStream
import java.util.zip.CRC32
import java.util.zip.CheckedOutputStream
import java.io.FileNotFoundException


object QiniuZipUtil {
    val system = "五四制"
    val executors = Executors.newScheduledThreadPool(5)
    @Throws(IOException::class)
    @JvmStatic
    fun main(args: Array<String>) {
        while (true) {
            println("请输入路径")
            val scanner = Scanner(System.`in`)
            val path = scanner.nextLine()

            println("请输入年级")
            val gradlescanner = Scanner(System.`in`)
            val grade = gradlescanner.nextLine()

            executors.submit {
                compressCourse(File(path), grade)
//            deleteWmv(file)
                println("$system 学制$grade 压缩完成")
            }
        }
    }

    private fun getPrefix(title: String, grade: String): String {
        if (title.contains("爱背卷") || title.contains("测查卷") || title.contains("语文园地")) {
            return grade
        } else {
            return ""
        }
    }

    private fun getName(file: File): String {
        val split = file.name.split(".")
        val sb = StringBuffer()
        for (i in 0..split.size - 1) {
            sb.append(split[i])
        }
        return sb.toString()
    }


    val BUFFER = 8192

    @Throws(IOException::class)
    fun compress(srcPath: String, dstPath: String) {
        val srcFile = File(srcPath)
        val dstFile = File(dstPath)
        if (!srcFile.exists()) {
            throw FileNotFoundException(srcPath + "不存在！")
        }

        var out: FileOutputStream? = null
        var zipOut: ZipOutputStream? = null
        try {
            out = FileOutputStream(dstFile)
            val cos = CheckedOutputStream(out, CRC32())
            zipOut = ZipOutputStream(cos)
            val baseDir = ""
            compress(srcFile, zipOut, baseDir)
        } finally {
            if (null != zipOut) {
                zipOut.close()
                out = null
            }

            out?.close()
        }
    }

    @Throws(IOException::class)
    private fun compress(file: File, zipOut: ZipOutputStream, baseDir: String) {
        if (file.isDirectory) {
            compressDirectory(file, zipOut, baseDir)
        } else {
            compressFile(file, zipOut, baseDir)
        }
    }

    /** 压缩一个目录  */
    @Throws(IOException::class)
    private fun compressDirectory(dir: File, zipOut: ZipOutputStream, baseDir: String) {
        val files = dir.listFiles()
        for (i in files!!.indices) {
            compress(files[i], zipOut, baseDir + dir.name + "/")
        }
    }

    /** 压缩一个文件  */
    @Throws(IOException::class)
    private fun compressFile(file: File, zipOut: ZipOutputStream, baseDir: String) {
        if (!file.exists()) {
            return
        }

        var bis: BufferedInputStream? = null
        try {
            bis = BufferedInputStream(FileInputStream(file))
            val entry = ZipEntry(baseDir + file.name)
            zipOut.putNextEntry(entry)
            val data = ByteArray(BUFFER)
            var count = bis.read(data, 0, BUFFER)
            while ((count) != -1) {
                zipOut.write(data, 0, count)
                count = bis.read(data, 0, BUFFER)
            }

        } finally {
            bis?.close()
        }
    }

    private fun deleteWmv(file: File) {
        println(file.name)
        if (file.isDirectory) {
            for (f in file.listFiles()) {
                deleteWmv(f)
            }
        } else {
            if (file.name.endsWith(".wmv")) {
                println(file.name)
            }
        }
    }

    private fun compressCourse(src: File, grade: String) {
        if (src.isDirectory) {
            for (file in src.listFiles()) {
                if (file.name.contains("output")) {
                    return;
                }
                if (file.isDirectory) {
                    compress(
                        file.absolutePath,
                        "${getSaveDir(grade)}/${getName(file)}（$system）${getPrefix(file.name, grade)}.zip"
                    )
                }
            }
        }
    }

    private fun getSaveDir(grade: String): String {
        val f = File("/Users/xzwzz/Desktop/$system/$grade")
        if (!f.exists()) {
            f.mkdirs()
        }
        return f.absolutePath
    }
}